package org.jground.rx.ui.zk.docu;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.dbfs.IDBFile;
import org.jground.dbfs.IDBFileService;
import org.jground.rx.RXLangStrings;
import org.jground.rx.RXSystem;
import org.jground.zk.zulX.HboxX;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Html;
import org.zkoss.zul.Popup;
import org.zkoss.zul.Toolbarbutton;

public class UIFileDownload2 extends HboxX implements EventListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Log logger = LogFactory.getLog(UIFileDownload2.class);

	private Popup popup = new Popup();
	private Toolbarbutton downloadLink = new Toolbarbutton();
	private boolean downloadOk;
	private IDBFile file;

	private static RXLangStrings downloadTheFile = new RXLangStrings();

	static {
		downloadTheFile.setDefault("Download the file ");
		downloadTheFile.add("en", "Download the file ");
		downloadTheFile.add("de", "Local speichern der Datei ");
	}

	public UIFileDownload2() {
		downloadLink.addEventListener(Events.ON_CLICK, this);
		add(downloadLink);
		//
		add(popup);
	}

	public void setContentType(String contentType) {
		// this.contentType = contentType;
	}

	public void setFile(IDBFile file) {
		this.file = file;
		IDBFileService fs = RXSystem.getInstance().getFileService();
		try {
			downloadLink.setLabel(file.getName());
			if (!fs.isAvailable(file)) {
				Html html = new Html("File " + file.getName()
						+ " not available for download!");
				html.setParent(popup);
				downloadLink.setTooltiptext("-no file found-");
				downloadOk = false;
			} else {
				downloadOk = true;
				downloadLink.setTooltiptext(downloadTheFile + file.getName());
			}
		} catch (Exception e) {
			logger.error(e, e);
		}
	}

	public void setLabel(String label) {
		downloadLink.setLabel(label);
	}

	public void onEvent(Event event) throws Exception {
		if (event.getTarget() == downloadLink) {
			if (file == null || downloadOk == false) {
				popup.open(downloadLink);
			} else {
				IDBFileService fs = RXSystem.getInstance().getFileService();
				try {
					// Filedownload.save(file, null, file.getName());
					Filedownload.save(fs.getInputStream(file), null,
							file.getName());
				} catch (Exception e) {
					logger.error(e, e);
				}
			}
		}
	}
}
